package com.ruoyi.pingjiao.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pingjiao.domain.Metaclass;
import com.ruoyi.pingjiao.mapper.MetaclassMapper;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.pingjiao.mapper.TeacherMapper;
import com.ruoyi.pingjiao.domain.Teacher;
import com.ruoyi.pingjiao.service.ITeacherService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 教师管理Service业务层处理
 *
 * @author 胡浩鹏
 * @date 2022-10-15
 */
@Service
@Slf4j
public class TeacherServiceImpl implements ITeacherService
{
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private MetaclassMapper metaclassMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
//    @Autowired
//    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 查询教师管理
     *
     * @param teacherId 教师管理主键
     * @return 教师管理
     */
    @Override
    public Teacher selectTeacherByTeacherId(Long teacherId)
    {
        return teacherMapper.selectTeacherByTeacherId(teacherId);
    }
    @Override
    public Teacher selectTeacherByUserId(Long userId)
    {
        return teacherMapper.selectTeacherByUserId(userId);
    }

    @Override
    public Teacher selectTeacherWithCourseByTeacherId(Long teacherId) {
        return teacherMapper.selectTeacherWithCourseByTeacherId(teacherId);
    }

    @Override
    public List<Metaclass> selectMetaclassByTeacherIdAndCourseclassId(Long courseclassId, Long teacherId) {
        return metaclassMapper.selectMetaclassByTeacherIdVo(courseclassId, teacherId);
    }

    /**
     * 查询教师管理列表
     *
     * @param teacher 教师管理
     * @return 教师管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<Teacher> selectTeacherList(Teacher teacher)
    {
        return teacherMapper.selectTeacherList(teacher);
    }

    /**
     * 新增教师管理
     *
     * @param teacher 教师管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTeacher(Teacher teacher)
    {
        teacher.setCreateTime(DateUtils.getNowDate());
        int i = teacherMapper.insertTeacher(teacher);
        SysUser user = new SysUser();
        user.setNickName(teacher.getRealName());
        user.setDeptId(teacher.getDeptId());
        user.setSex(teacher.getGender());
        user.setStuOrTeaId(teacher.getTeacherId());
        user.setUserName(teacher.getTeacherNo());
        user.setPassword(SecurityUtils.encryptPassword("123456"));

        userMapper.insertUser(user);

        SysRole role = new SysRole();
        role.setRoleName("教师");
        List<SysRole> sysRoles = roleMapper.selectRoleList(role);

        List<SysUserRole> list = new ArrayList<SysUserRole>();
        SysUserRole ur = new SysUserRole();
        ur.setUserId(user.getUserId());
        ur.setRoleId(sysRoles.get(0).getRoleId());
        list.add(ur);
        userRoleMapper.batchUserRole(list);

        teacher.setUserId(user.getUserId());
        teacherMapper.updateTeacher(teacher);

        return i;
    }

    /**
     * 修改教师管理
     *
     * @param teacher 教师管理
     * @return 结果
     */
    @Override
    public int updateTeacher(Teacher teacher)
    {
        teacher.setUpdateTime(DateUtils.getNowDate());
        return teacherMapper.updateTeacher(teacher);
    }

    /**
     * 批量删除教师管理
     *
     * @param teacherIds 需要删除的教师管理主键
     * @return 结果
     */
    @Override
    public int deleteTeacherByTeacherIds(Long[] teacherIds)
    {
        return teacherMapper.deleteTeacherByTeacherIds(teacherIds);
    }

    /**
     * 删除教师管理信息
     *
     * @param teacherId 教师管理主键
     * @return 结果
     */
    @Override
    public int deleteTeacherByTeacherId(Long teacherId)
    {
        return teacherMapper.deleteTeacherByTeacherId(teacherId);
    }

    /**
     * 根据教师工号获取教师信息
     * @author  hpf
     * @param  teacherNo 教工号
     * @return 教师
     */
    @Override
    public Teacher selectTeacherByNo(String  teacherNo){
        return  teacherMapper.selectTeacherByNo(teacherNo);
    }

    /**
     * 根据教师id获取本学期评教成绩
     * @author  hpf
     * @param  teacherId 教工id
     * @return 教师
     */
    @Override
    public List<Map<String, Object>> selectEvaluationScoreByTeacherId(Long  teacherId,Long activityId){
        Map<String,Object> map =new HashMap<>();
        map.put("teacherId",teacherId);
        map.put("activityId",activityId);
        return  teacherMapper.selectEvaluationScoreByTeacherId(map);
    }

    /**
     * 根据教师id获取本学期评教活动
     * @author  hpf
     * @param  teacherId 教工id
     * @return 教师
     */
    public List<Map<String, Object>> selectActivityByTeacherId(Long teacherId, String term){
        Map<String,Object> map =new HashMap<>();
        map.put("teacherId",teacherId);
        map.put("term",term);
        return  teacherMapper.selectActivityByTeacherId(map);
    }

    @Override
    public Object getInfoByUserId(Long userId) {
        return teacherMapper.getInfoByUserId(userId);
    }

    @Override
    public List<Map<String,Object>> getRank(Long teacherId) {
        return teacherMapper.getRank(teacherId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importTeacher(List<Teacher> teacherList, String operName) {
        if (StringUtils.isNull(teacherList) || teacherList.isEmpty()) {
            throw new ServiceException("导入教师数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Teacher teacher : teacherList) {

            try {


                SysDept sysDept = sysDeptMapper.selectDeptByDeptName(teacher.getDeptName());
                // 根据教师工号号查询教师
                Teacher tea2 = teacherMapper.selectTeacherByTeacherNo(teacher.getTeacherNo());


                if (!StringUtils.isNull(sysDept) && StringUtils.isNull(tea2)) {
                    teacher.setDeptId(sysDept.getDeptId());
                    // 不存在
                    // 插入 教师
                    SysUser selectUser = randomTeacherUser(teacher);
                    teacher.setCreateBy(SecurityUtils.getLoginUser().getUsername());
                    teacher.setUserId(selectUser.getUserId());
                    teacher.setCreateTime(DateUtils.getNowDate());
                    teacherMapper.insertTeacher(teacher);
                    SysUserRole sysUserRole=new SysUserRole();
                    sysUserRole.setRoleId(Long.valueOf(102));
                    sysUserRole.setUserId(selectUser.getUserId());
                    sysUserRoleMapper.insert(sysUserRole);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、教师 " + teacher.getRealName() + " 导入成功");
                } else {
                    // 存在  不支持更新
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、教师 " + teacher.getRealName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、教师 " + teacher.getRealName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "共 " + failureNum + " 条数据格式不正确并导入失败，错误如下：");
        }
        if (successNum > 0) {
            successMsg.insert(0, "共 " + successNum + " 条导入成功，数据如下：");
        }
        return successMsg.toString() + "<br/>" + failureMsg.toString();

    }

    /**
     * 给教师分配用户
     *
     * @param teacher
     * @return
     */
    private SysUser randomTeacherUser(Teacher teacher) {
        // 给教师分配用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(teacher.getTeacherNo());
        sysUser.setPassword(SecurityUtils.encryptPassword(teacher.getTeacherNo()));
        sysUser.setNickName(teacher.getRealName());
        sysUser.setRemark("教师");
//        sysUser.setPhonenumber(teacher.get());
        sysUser.setDeptId(teacher.getDeptId());
        if ("男".equals(teacher.getGender())) {
            sysUser.setSex("0");
        } else if ("女".equals(teacher.getGender())) {
            sysUser.setSex("1");
        } else {
            sysUser.setSex("2");
        }
        sysUser.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        userMapper.insertUser(sysUser);
        // 查询刚插入的用户
        return userMapper.selectUserByUserName(teacher.getTeacherNo());
    }

}
